/* Copyright 2011 Google Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * Project home page: http://code.google.com/p/usb-serial-for-android/
 */

package com.hoho.android.usbserial.examples;

import android.app.Activity;
import android.content.Context;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.hoho.android.usbserial.R;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.examples.Model.DataPacket;
import com.hoho.android.usbserial.util.HexDump;
import com.hoho.android.usbserial.util.SerialInputOutputManager;
import com.hoho.android.usbserial.examples.Model;
import com.hoho.android.usbserial.examples.SaveData;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * A sample Activity demonstrating USB-Serial support.
 *
 * @author mike wakerly (opensource@hoho.com)
 */
public class DemoActivity extends Activity {

    private final String TAG = DemoActivity.class.getSimpleName();

    /**
     * The device currently in use, or {@code null}.
     */
    private UsbSerialDriver mSerialDevice;

    /**
     * The system's USB service.
     */
    private UsbManager mUsbManager;

    private TextView status;
    private TextView val1Text;
    private TextView val2Text;
    private Button button;

    private final ExecutorService mExecutor = Executors.newSingleThreadExecutor();

    private SerialInputOutputManager mSerialIoManager;

    private final SerialInputOutputManager.Listener mListener =
            new SerialInputOutputManager.Listener() {

        @Override
        public void onRunError(Exception e) {
            Log.d(TAG, "Runner stopped.");
        }

        @Override
        public void onNewData(final byte[] data) {
            DemoActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    DemoActivity.this.updateReceivedData(data);
                }
            });
        }
    };

    /**
     * Private Variables
     */
    private SaveData save;
    private Model model;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        status = (TextView) findViewById(R.id.status);
        val1Text = (TextView) findViewById(R.id.val1Text);
        val2Text = (TextView) findViewById(R.id.val2Text);
        button = (Button) findViewById(R.id.button);
        

        save = new SaveData(this);
        model= new Model(this);
        
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopIoManager();
        if (mSerialDevice != null) {
            try {
                mSerialDevice.close();
            } catch (IOException e) {
                // Ignore.
            }
            mSerialDevice = null;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mSerialDevice = UsbSerialProber.acquire(mUsbManager);

        if (mSerialDevice == null) {
            status.setText("Nessun device connesso.");
        } else {
            try {
                mSerialDevice.open();
            } catch (IOException e) {

                status.setText("Errore connessione device: " + e.getMessage());
                try {
                    mSerialDevice.close();
                } catch (IOException e2) {
                    // Ignore.
                }
                mSerialDevice = null;
                return;
            }
            status.setText("Device connesso.");
            //ogni volta che attacco un device diverso, azzero il numero di file
            save.resetFileNumber();
        }
        onDeviceStateChange();
    }

    private void stopIoManager() {
        if (mSerialIoManager != null) {

            mSerialIoManager.stop();
            mSerialIoManager = null;
        }
    }
    
    private boolean isRecording=false;
    
    public void recordData(View _view){
        if(!isRecording){
            
            save.resetFileNumber();
            try {
                save.createWriter();
            } catch (Exception e) {
                //status.setText("Errore, impossibile creare il file");
                return;
            }
            

            //ogni volta che avvio il listener, azzero il numero di file
            
            
            
            mExecutor.submit(mSerialIoManager);
            isRecording=true;
            button.setText("Arresta");
        }else{
            mSerialIoManager.stop();
            mSerialIoManager = new SerialInputOutputManager(mSerialDevice, mListener);
            isRecording=false;
            button.setText("Avvia");
            save.closeWriter();
        }
        
    }
    
    private void startIoManager() {
        if (mSerialDevice != null) {

            mSerialIoManager = new SerialInputOutputManager(mSerialDevice, mListener);
            
        }
    }

    private void onDeviceStateChange() {
        stopIoManager();
        startIoManager();
    }

    private void updateReceivedData(byte[] data) {

        try{
        model.addString(HexDump.dumpString(data));
        }catch(Exception ex){
            return;
        }
    }

    public void write(DataPacket p) {

        // TODO Auto-generated method stub
        val1Text.setText(String.valueOf(p.val1));
        val2Text.setText(String.valueOf(p.val2));
        
        

        save.write(p.toString());
    }
    public void error(String s){
        status.setText(s);
    }
    

    
}
